<?php
class Controller_Services_MessageTemplate extends Controller_Abstract
{
	function actionCreate()
	{
		$this->_view['title'] = '创建模板';
	}
	
	function actionCreateSave()
	{
		$this->_view['title'] = '创建模板（保存）';
		if ($_POST['name'] && $_POST['body'])
		{
			$result = Services_Message_Template::find('name=?', $_POST['name'])->asArray()->getOne();
			if (! $result)
			{
				$template = array(
					'name' => $_POST['name'],
					'body' => $_POST['body']
				);
				$edit_result = Services_Message_Template::create($template);
				if ($edit_result['ack'] == SUCCESS)
				{
					return $this->_redirectMessage('创建成功', '返回列表', url('Services::MessageTemplate/List'), $edit_result['ack']);
				}
			}
			else
			{
				return $this->_redirectMessage('创建失败', '模板名称已经存在', $_SERVER['HTTP_REFERER'], FAILURE);
			}
		}
		else
		{
			return $this->_redirectMessage('创建失败', '输入框不能为空', $_SERVER['HTTP_REFERER'], FAILURE);
		}
	}
	
	function actionList()
	{
		$this->_view['title'] = '模板列表';
		$ps = isset($_GET['ps']) ? $_GET['ps'] : '20';
		$cp = isset($_GET['cp']) ? $_GET['cp'] : '1';
		$url_arr = Helper_BSS_Normal::buildCondition();
		$result = Services_Message_Template::search($url_arr, $cp, $ps);
		if ($result['ack'] == SUCCESS)
		{
			$page = new Helper_BSS_Page($result['pagination'], url('Services::MessageTemplate/List', $url_arr));
			$this->_view['page'] = $page->getPage();
			$this->_view['template'] = $result['data'];
		}
	}
	
	function actionEdit()
	{
		$this->_view['title'] = '模板编辑';
		$template = Services_Message_Template::find('services_message_template.id=?', $_GET['id'])
			->joinLeft('user', 'user.name as create_user_name', 'services_message_template.create_user_id=user.id')
			->asArray()->getOne();
		if ($template)
		{
			$this->_view['template'] = $template;
		}
		else
		{
			return $this->_redirectMessage('编辑失败', '没有找到邮件模板内容', $_SERVER['HTTP_REFERER'], FAILURE);
		}
	}
	
	function actionEditSave()
	{
		$this->_view['title'] = '模板编辑保存';
		if ($_POST['name'] && $_POST['body'])
		{
			QDB::getConn()->execute('update services_message_template set name=\'' . $_POST['name'] . '\',body=\'' . mysql_escape_string($_POST['body']) . '\' where id=' . $_POST['id']);
			return $this->_redirectMessage('编辑成功', '正在返回列表...', url('Services::MessageTemplate/List'), SUCCESS);
		}
		else
		{
			return $this->_redirectMessage('编辑失败', '输入框不能为空', $_SERVER['HTTP_REFERER'], FAILURE);
		}
	}
}